package com.googlecode.serialization;

import java.io.UnsupportedEncodingException;

public class StringTranscoder extends AbsPrimitiveTypeTranscoder<String> {
	private String charset = AbsSerializingTranscoder.DEFAULT_CHARSET;
	public static final int STRING_FLAG = 0;

	public StringTranscoder(String charset) {
		this.charset = charset;
	}

	public StringTranscoder() {
		this(AbsSerializingTranscoder.DEFAULT_CHARSET);
	}
	
	@Override
	public String decode(DataInfo d) {
		if (d.getFlag() == 0) {
			String rv = null;
			try {
				if (d.getData() != null) {
					rv = new String(d.getData(), this.charset);
				}
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
			return rv;
		} else {
			throw new RuntimeException("Decode String error");
		}
	}

	@Override
	public DataInfo encode(String s) {
		byte[] b = null;

		try {
			b = s.getBytes(this.charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		return new DataInfo(STRING_FLAG, b);
	}

}
